package com.cn.esermis.config;

import com.alibaba.fastjson.JSON;
import com.cn.esermis.dpld.mapper.DataAcquisitionInstrumentMapper;
import com.cn.esermis.model.BaseUser;
import com.cn.esermis.utils.TokenUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component //
public class MyInterceptor  implements HandlerInterceptor  {


    private static final String AUTH_HEADER = "Authorization";
    private static final String TOKEN_PREFIX = "Bearer ";
    @Resource
    DataAcquisitionInstrumentMapper dataAcquisitionInstrumentMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 header 中的 Authorization 信息
//        String token = request.getHeader("Authorization");

        String token = extractToken(request);
        if (token != null) {
            BaseUser userInfo = TokenUtils.getUserInfo(token);
            if (userInfo != null){
                // 查询数据库是否有 公司和工厂信息
                String verifyCompany = dataAcquisitionInstrumentMapper.verifyCompany(userInfo.getCompanyId());
//                Boolean verifydepartmen = dataAcquisitionInstrumentMapper.verifydepartmen(userInfo.getFactoryId());
                if (verifyCompany!=null){
                    // 将用户信息设置到请求属性中，便于后续使用
                    userInfo.setLevelid(verifyCompany);
                    request.setAttribute("userInfo", JSON.toJSONString(userInfo));
                    return true;
                }else {
                    throw new BizException("403","用户无权限！");
                }
            }else{
                throw new BizException("403","token解析失败！");
            }
        }else {
//            throw new BizException("403","token为空！");
            return true;
        }

    }

    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader(AUTH_HEADER);
        if (bearerToken != null && bearerToken.startsWith(TOKEN_PREFIX)) {
            return bearerToken.substring(TOKEN_PREFIX.length());
        }
        return null;
    }
}